package com.pig4cloud.pig.module.controller.wx;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.api.entity.wx.WxUserCashRecord;
import com.pig4cloud.pig.module.service.wx.IWxUserCashRecordService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信提现记录Controller
 *
 * @author ruoyi
 * @date 2022-05-14
 */
@Validated
@Api(value = "微信提现记录控制器", tags = {"微信提现记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/cash/record")
public class WxUserCashRecordController {

    private final IWxUserCashRecordService wxUserCashRecordService;
	private final IWxUserService wxUserService;

    /**
     * 查询微信提现记录列表
     */
    @ApiOperation("查询微信提现记录列表")
    @PreAuthorize("@pms.hasPermission('module:cashRecord:list')")
    @GetMapping("/list")
    public TableDataInfo<WxUserCashRecord> list(@Validated WxUserCashRecord wxUserCashRecord) {
        QueryWrapper<WxUserCashRecord> qw = new QueryWrapper<>();
        if(wxUserCashRecord.getMerId()!=null){
        	qw.eq("mer_id",wxUserCashRecord.getMerId());
		}
		if(wxUserCashRecord.getPayState()!=null){
			qw.eq("pay_state",wxUserCashRecord.getPayState());
		}
		if(StrUtil.isNotEmpty(wxUserCashRecord.getBeginDate())){
			qw.between("create_time",wxUserCashRecord.getBeginDate() + " 00:00:00",
				wxUserCashRecord.getEndDate() + " 23:59:59");
		}

        qw.orderByDesc("create_time");
        TableDataInfo<WxUserCashRecord> td = PageUtils.buildDataInfo(wxUserCashRecordService.page(PageUtils.buildPage(),qw));
        List<WxUserCashRecord> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for(WxUserCashRecord cashRecord : list){
        		WxUser wxUser = wxUserService.findById(cashRecord.getUserId());
        		if(wxUser!=null){
        			if(StrUtil.isNotEmpty(wxUser.getNickName())){
						cashRecord.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
					}
				}
			}
		}
        return td;
    }

    /**
     * 导出微信提现记录列表
     */
    @ApiOperation("导出微信提现记录列表")
    @PreAuthorize("@pms.hasPermission('module:cashRecord:export')")
    @SysLog("微信提现记录")
    @GetMapping("/export")
    public List export(@Validated WxUserCashRecord wxUserCashRecord) {
		QueryWrapper<WxUserCashRecord> qw = new QueryWrapper<>();

		if(wxUserCashRecord.getMerId()!=null){
			qw.eq("mer_id",wxUserCashRecord.getMerId());
		}

		if(wxUserCashRecord.getPayState()!=null){
			qw.eq("pay_state",wxUserCashRecord.getPayState());
		}
		qw.orderByDesc("create_time");

		List<WxUserCashRecord> list = wxUserCashRecordService.list(qw);
		if(CollUtil.isNotEmpty(list)){
			for (WxUserCashRecord cashRecord : list){
				cashRecord.setCreateTimeStr(DateUtils.getTime(cashRecord.getCreateTime()));
				if(cashRecord.getCheckTime()!=null){
					cashRecord.setCheckTimeStr(DateUtils.getTime(cashRecord.getCheckTime()));
				}
				if(cashRecord.getPayTime()!=null){
					cashRecord.setPayTimeStr(DateUtils.getTime(cashRecord.getPayTime()));
				}

				//支付状态 提现支付状态 0 - 待审核   1 - 支付成功  2 - 支付失败  3 - 拒绝支付
				if(cashRecord.getPayState() ==0){
					cashRecord.setPayStateStr("待审核");
				} else if(cashRecord.getPayState() ==1){
					cashRecord.setPayStateStr("支付成功");
				} else if(cashRecord.getPayState() ==2){
					cashRecord.setPayStateStr("支付失败");
				} else if(cashRecord.getPayState() ==3){
					cashRecord.setPayStateStr("拒绝支付");
				}
			}
		}

        // ExcelUtil<WxUserCashRecord> util = new // ExcelUtil<>(WxUserCashRecord.class);
        return  list;// util.exportExcel(list, "微信提现记录");
    }

    /**
     * 获取微信提现记录详细信息
     */
    @ApiOperation("获取微信提现记录详细信息")
    @PreAuthorize("@pms.hasPermission('module:cashRecord:query')")
    @GetMapping("/{id}")
    public R<WxUserCashRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") String id) {
        WxUserCashRecord wxUserCashRecord = wxUserCashRecordService.getById(id);
        if(wxUserCashRecord!=null){
			WxUser wxUser = wxUserService.findById(wxUserCashRecord.getUserId());
			if(wxUser != null){
				if(StrUtil.isNotEmpty(wxUser.getNickName())){
					wxUserCashRecord.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
				}
			}
		}
        return R.ok(wxUserCashRecord);
    }

    /**
     * 新增微信提现记录
     */
    @ApiOperation("新增微信提现记录")
    @PreAuthorize("@pms.hasPermission('module:cashRecord:add')")
    @SysLog("微信提现记录")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody WxUserCashRecord wxUserCashRecord) {
        return R.okByRow(wxUserCashRecordService.save(wxUserCashRecord) ? 1 : 0);
    }

	/**
	 * 修改微信提现记录
	 */
	@ApiOperation("修改微信提现记录")
	@PreAuthorize("@pms.hasPermission('module:cashRecord:edit')")
	@SysLog("微信提现记录")

	@PutMapping()
	public R<Void> edit(@Valid @RequestBody WxUserCashRecord wxUserCashRecord) {
		PigUser sysUser = SecurityUtils.getUser();
		wxUserCashRecord.setCheckSysUserId(sysUser.getId());
		wxUserCashRecord.setCheckSysUserName(sysUser.getName());
		wxUserCashRecord.setCheckTime(new Date());
		boolean bl = false;
		if(wxUserCashRecord.getCheckState() == 1){
			Map<String,Object> map = wxUserCashRecordService.checkRecord(wxUserCashRecord);
			if(map.containsKey("result_code")){
			    if(map.get("result_code").equals("SUCCESS")){
                    return R.okByRow(1);
                } else {
                    return R.failed(map.get("err_code_des").toString());
                }
            }
            return R.okByRow(0);
		}else{
			bl = wxUserCashRecordService.updateById(wxUserCashRecord);
		}
		return R.okByRow(bl ? 1 : 0);
	}

    /**
     * 删除微信提现记录
     */
    @ApiOperation("删除微信提现记录")
    @PreAuthorize("@pms.hasPermission('module:cashRecord:remove')")
    @SysLog("微信提现记录")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable String[] ids) {
        return R.okByRow(wxUserCashRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
